package com.example.compose

import android.annotation.SuppressLint
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.draw.scale
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import coil.compose.AsyncImage
import coil.request.ImageRequest
import kotlin.math.absoluteValue
import kotlin.math.roundToInt


@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun MyApp() {
    MaterialTheme {
        Scaffold(
            topBar = {
                TopAppBar(title = { Text("Accompanist Pager") })
            }
        ) {
            PagerExample()
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PagerExample() {
    val pages = listOf(Color.Red, Color.Green, Color.Blue)
    val pagerState = rememberPagerState(pageCount = { pages.size })

    HorizontalPager(
        state = pagerState,
        modifier = Modifier.fillMaxSize()
    ) { page ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(pages[page])
        ) {
            Text(
                text = "Page ${page + 1}",
                modifier = Modifier.align(Alignment.Center),
                color = Color.White,
                style = MaterialTheme.typography.titleMedium
            )
        }
    }
}

data class Place(
    val name: String,
    val resId: Int
)

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ReflectionAnimation() {
    val places = listOf(
        Place("nox", R.drawable.nox),
        Place("bella", R.drawable.bella),
        Place("koda", R.drawable.koda),
        Place("lola", R.drawable.lola),
        Place("leroy", R.drawable.leroy),
        Place("tzeitel", R.drawable.tzeitel),
    )

    val pager = rememberPagerState(
        initialPage = 0,
        initialPageOffsetFraction = 0f,
        pageCount = { places.size }
    )

    val bgColor by animateColorAsState(
        targetValue = if (pager.currentPage % 2 == 0) {
            Color(0xffe2e7ff)
        } else {
            Color(0xff090d1f)
        },
        animationSpec = tween(durationMillis = 500),
        label = "bgColor animate"
    )
    val textColor by animateColorAsState(
        targetValue = if (pager.currentPage % 2 == 0) {
            Color.Black
        } else {
            Color.White
        },
        animationSpec = tween(durationMillis = 500),
        label = "textColor animate"
    )

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(color = bgColor),
        contentAlignment = Alignment.Center
    ) {
        HorizontalPager(
            state = pager,
            contentPadding = PaddingValues(75.dp),
            key = { places[it].resId },
            modifier = Modifier.fillMaxSize()
        ) { index ->

            val imgScale by animateFloatAsState(
                targetValue = if (index == pager.currentPage) 1.3f else 1f,
                animationSpec = tween(durationMillis = 500),
                label = "imgScale"
            )
            val reflectionAlpha by animateFloatAsState(
                targetValue = if (index == pager.currentPage) 0.8f else 0.2f,
                animationSpec = tween(durationMillis = 500),
                label = "reflectionAlpha"
            )
            val imgOffset by animateDpAsState(
                targetValue = if (index == pager.currentPage) 80.dp else 4.dp,
                animationSpec = tween(durationMillis = 500),
                label = "imgOffset"
            )
            val letterSpace by animateFloatAsState(
                targetValue = if (index == pager.currentPage) 8f else 0f,
                animationSpec = tween(durationMillis = 600),
                label = "letterSpace"
            )

            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = places[index].name,
                    fontSize = 30.sp,
                    color = textColor,
                    letterSpacing = TextUnit(letterSpace, TextUnitType.Sp)
                )
                Spacer(modifier = Modifier.height(60.dp))
                Image(
                    painter = painterResource(id = places[index].resId),
                    contentDescription = places[index].name,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .height(250.dp)
                        .aspectRatio(3 / 4f)
                        .scale(imgScale)
                        .clip(RoundedCornerShape(8.dp))
                )
                Image(
                    painter = painterResource(id = places[index].resId),
                    contentDescription = places[index].name,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .height(250.dp)
                        .aspectRatio(3 / 4f)
                        .offset(y = imgOffset)
                        .scale(imgScale, -imgScale)
                        .clip(RoundedCornerShape(8.dp))
                        .graphicsLayer {
                            alpha = reflectionAlpha
                        }
                        .drawWithContent {
                            val overlayColor = listOf(
                                Color.Transparent,
                                Color.Transparent,
                                Color.Transparent,
                                Color.White
                            )
                            drawContent()
                            drawRect(
                                brush = Brush.verticalGradient(overlayColor),
                                blendMode = BlendMode.DstIn
                            )
                        }
                )
            }
        }
    }
}

@Composable
fun AccordionLazyRow(modifier: Modifier = Modifier) {
    var width by remember {
        mutableFloatStateOf(1f)
    }
    LazyRow(
        modifier = modifier.onSizeChanged {
            width = it.width.toFloat()
        },
        verticalAlignment = Alignment.CenterVertically,
        contentPadding = PaddingValues(horizontal = 80.dp)
    ) {
        items(count = 100) { page ->
            var x by remember {
                mutableFloatStateOf(0f)
            }
            val zIndex by remember {
                derivedStateOf {
                    (width - (x - (width / 2)).absoluteValue).toInt().toFloat()
                }
            }
            Box(
                modifier = Modifier
//                    .zIndex(zIndex)
                    .requiredWidth(40.dp)
            ) {
                AsyncImage(
                    model = ImageRequest.Builder(LocalContext.current)
                        .data("https://source.unsplash.com/random/1920x1080/?greece,$page")
                        .crossfade(enable = true).build(),
                    contentDescription = null,
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .onGloballyPositioned { x = it.positionInWindow().x }
                        .graphicsLayer {
                            rotationY = (x / width).lerp(0f, 90f)
                            transformOrigin = TransformOrigin(1f, 5f)
                            cameraDistance = 10f
                        }
                        .height(120.dp)
                        .requiredWidth(300.dp)
                        .shadow(
                            elevation = 10.dp,
                            shape = RoundedCornerShape(20.dp),
                            spotColor = Color.Black.copy(alpha = 0.2f)
                        )
                        .clip(RoundedCornerShape(20.dp))
                        .background(color = Color(0xfffff9e6))
                )
            }
        }
    }
}

fun Float.lerp(start: Float, end: Float) = start + this * (end - start)

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    AccordionLazyRow(modifier = Modifier.fillMaxSize())
}


